import Vue from "vue";
import VueRouter from "vue-router";
import HomeView from "../views/Home.vue";
import store from "@/store";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    redirect: "/home",
  },
  {
    path: "/home",
    name: "home",
    component: HomeView,
  },
  {
    path: "/free",
    name: "free",
    component: () => import("../views/Free.vue"),
  },
  {
    path: "/goods",
    name: "goods",
    component: () => import("../views/Goods.vue"),
  },
  {
    path: "/mine",
    name: "mine",
    component: () => import("../views/Mine.vue"),
  },
  {
    path: "/user",
    name: "user",
    redirect: "/user/cart",
    component: () => import("../views/User.vue"),
    children: [
      {
        path: "cart",
        component: () => import("../components/user/Cart.vue"),
      },
    ],
    // beforeEnter: (to, from, next) => {
    //   if (to.path == "/user") {
    //     let token = localStorage.getItem("x-auth-token");
    //     if (token) {
    //       next();
    //     } else {
    //       store.dispatch("showToast/asyncChangeToast", {
    //         isShow: true,
    //         type: "error",
    //         title: "请先登录",
    //       });
    //     }
    //   }
    // },
  },
  {
    path: "/details",
    name: "details",
    component: () => import("../views/Details.vue"),
  },
];

// 解决路由连续点击错误
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location) {
  return originalPush.call(this, location).catch((err) => {});
};

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});

// 全局前置守卫
// 去任何一个地方都会被触发
// router.beforeEach((to, from, next) => {
//   // console.log(to, from);
//   if (to.path == "/user") {
//     let token = localStorage.getItem("x-auth-token");
//     if (token) {
//       next();
//     } else {
//       store.dispatch("showToast/asyncChangeToast", {
//         isShow: true,
//         type: "warning",
//         title: "请先登录",
//       });
//     }
//   } else {
//     next();
//   }
// });

export default router;
